// 公共函数库
import dayjs from 'dayjs'

export const outActionName = name => {
  return name.split('_')[0] + '/' + name
}

// 防抖
export function debounce(func, delay = 300) {
  let timer
  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func.apply(this, args)
    }, delay)
  }
}

// 节流
export function throttle(func, delay = 300) {
  let lastTime = 0
  return function (...args) {
    const now = Date.now()
    if (now - lastTime >= delay) {
      func.apply(this, args)
      lastTime = now
    }
  }
}

// https://dayjs.fenxianglu.cn/category/manipulate.html#%E5%A2%9E%E5%8A%A0
// day week month year hour
export const formatAddDate = (day = -20, type = 'year') => {
  return dayjs().add(day, type).format('YYYY-MM-DD')
}

export const jsonToSearch = obj => {
  return Object.keys(obj)
    .map(key => `${key}=${obj[key]}`)
    .join('&')
}

export const isPlainObject = obj => {
  return Object.prototype.toString.call(obj) === '[object Object]'
}

// 给一个File文件生成ArrayBuffer
export const fileToBuffer = file => {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader()
    fileReader.readAsArrayBuffer(file)
    fileReader.onload = e => {
      resolve(e.target.result)
    }
    fileReader.onerror = err => reject(err)
  })
}

export const delay = (ms = 300) => {
  return new Promise(_ => {
    setTimeout(() => {
      _()
    }, ms)
  })
}
